package com.woyao;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.RegisterResponse;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;
import com.woyao.core.util.TimeCountUtil;

import java.io.IOException;
import java.util.List;

import retrofit2.Call;

public class RegisterActivity extends AppCompatActivity {

    private EditText username;
    private EditText password;
    private EditText verifyCode;
    private EditText refer_id;
    private Button register;
    private CheckBox checkBox;
    private boolean state = false;
    private ImageView backBtn;
    ProgressDialog progressDialog;

    String longitude = "0.0";
    String latitude = "0.0";
    private Integer MYLOGIN_CODE =100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_register);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true);
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true);
        this.setTitle("注册");

        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        verifyCode = (EditText) findViewById(R.id.code);
        checkBox = (CheckBox) findViewById(R.id.checkBox);
        refer_id = (EditText) findViewById(R.id.refer_id);

        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    state = true;
                } else {
                    state = false;
                }
            }
        });

        Button loginBtn = (Button) findViewById(R.id.id_login);

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(RegisterActivity.this, LoginActivity.class);

                startActivityForResult(intent,MYLOGIN_CODE);
            }
        });

        TextView agreeBtn = (TextView) findViewById(R.id.agreement);

        agreeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(RegisterActivity.this, WebviewActivity.class);
                intent.putExtra("title", "用户协议");
                intent.putExtra("link", "https://www.woyaooo.com/protocol.html");
                startActivity(intent);
            }
        });

        TextView privacyBtn = (TextView) findViewById(R.id.privacy);

        privacyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(RegisterActivity.this, WebviewActivity.class);
                intent.putExtra("title", "隐私政策");
                intent.putExtra("link", "https://www.woyaooo.com/privacy.html");
                startActivity(intent);
            }
        });


        register = (Button) findViewById(R.id.register);

//        Button login = (Button)findViewById(R.id.login);
        sendCode = (Button) findViewById(R.id.sendCode);

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkBox.isChecked()) {
                    register();
                } else {
                    Common.alert(RegisterActivity.this, "请同意用户协议");
//                    Toast.makeText(RegisterActivity.this, "请同意用户协议", Toast.LENGTH_LONG).show();
                }
            }
        });
//        login.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//                Intent intent = new Intent();
//                intent.setClass(RegisterActivity.this, LoginActivity.class);
//                startActivity(intent);
//            }
//        });
        sendCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCode();
            }
        });
//        TryGetCurrentLocation( );

        SharedPreferences shared = getSharedPreferences("login", MODE_PRIVATE);
        try {
            username.setText( shared.getString("mobile", ""));
        }catch (Exception e){
            Common.alert(RegisterActivity.this, "加载用户配置出错了");
        }
    }

    private String code = null;
    private Button sendCode = null;
    private Integer userId = null;
    private final static int MAX = 60;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        setResult(0, intent);
        finish();
        return true;
    }

    private void sendCode() {
//        code = RandomUtil.randomNumber(6);

        EditText username = (EditText) findViewById(R.id.username);
        if (StringUtil.isNullOrEmpty(username.getText().toString())) {
            username.setError("手机号必填");
            return;
        }
        if (username.length() != 11) {
            username.setError("手机号错误");
            return;
        }
        final String usernameText = username.getText().toString().trim();
        //
        TimeCountUtil timer = new TimeCountUtil(RegisterActivity.this, MAX * 1000, 1000, sendCode);
        timer.start();

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在发送中······");
        progressDialog.show();

        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.sendCode( WoyaoooApplication.key,WoyaoooApplication.userId, usernameText);
                BaseResponse body;
                try {
                    body = responseCall.execute().body();
                    return  body;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }

            }

            @Override
            protected void onPostExecute(final BaseResponse response) {

                if (response.isSuccess()) {
                     code = response.getMessage();
                } else {
                    verifyCode.setError("验证码发送错误!");
                    //todo 测试代码

                }
                progressDialog.dismiss();
//                verifyCode.setHint(code);
            }

            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void) null);

        verifyCode.requestFocus();
    }

    private void register() {
//        getCurrentLocation();
        if (StringUtil.isNullOrEmpty(username.getText().toString())) {
            username.setError("用户名必填");
            username.requestFocus();
            return;
        }
        final String usernameText = username.getText().toString().trim();
        if (usernameText == null || usernameText.length() != 11 || !usernameText.equals(username.getText().toString())) {
            username.setError("手机号错误");
            username.requestFocus();
            return;
        }
        if (StringUtil.isNullOrEmpty(password.getText().toString())) {
            password.setError("密码必填");
            password.requestFocus();
            return;
        }
        if (password.length() < 6) {
            password.setError("密码至少6位");
            password.requestFocus();
            return;
        }
        if (StringUtil.isNullOrEmpty(verifyCode.getText().toString())) {
            verifyCode.setError("验证码必填");
            verifyCode.requestFocus();
            return;
        }

        if (code == null || !code.equals(verifyCode.getText().toString())) {
            verifyCode.setError("验证码错误");
            verifyCode.requestFocus();
            return;
        }

        final String passwordText = password.getText().toString();


        final String referid = refer_id.getText().toString();
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("拼命处理中······");
        progressDialog.show();

        AsyncTask<Void, Void, RegisterResponse> task =
                new AsyncTask<Void, Void, RegisterResponse>() {
                    @Override
                    protected RegisterResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<RegisterResponse> call = svc.register( WoyaoooApplication.userId, usernameText, passwordText,referid,longitude,latitude,"android");
                        try {
                            RegisterResponse body = call.execute().body();

                            return body;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final RegisterResponse response) {
                        progressDialog.dismiss();
                        if (response != null) {
                            if (response.isSuccess()) {
                                LoginActivity.setLogin(getApplication(), response.getUserId() ,username.getText().toString());
//                                Intent intent = new Intent();
//                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                                intent.setClass(RegisterActivity.this, AccountActivity.class);
                                Intent intent = new Intent();
                                setResult(666, intent);
                                finish();
//                                startActivityForResult(intent,1);
                            }else{
                                Common.alert( RegisterActivity.this, response.getMessage());
                                password.requestFocus();
                            }
                        } else {
                            password.setError("系统错误，请重试");

                        }

                    }

                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute((Void) null);

    }

    public  void TryGetCurrentLocation() {

//        Activity context = RegisterActivity.this;
//        LocationManager locationManager;
//        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//        //获取所有可用的位置提供器
//        List<String> providers = locationManager.getProviders(true);
//        String locationProvider = null;
//        if (providers.contains(LocationManager.GPS_PROVIDER)) {
//            //如果是GPS
//            locationProvider = LocationManager.GPS_PROVIDER;
//        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
//            //如果是Network
//            locationProvider = LocationManager.NETWORK_PROVIDER;
//        } else {
////            Intent i = new Intent();
////            i.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
////            context.startActivity(i);
//            return ;
//        }
        //获取Location
        if (ActivityCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        } else {
            getCurrentLocation();
        }
    }
    public  void getCurrentLocation() {
        try {
            if (ActivityCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
               return;
            }

            LocationManager mLocationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
            List<String> all_providers = mLocationManager.getProviders(true);
            Location bestLocation = null;
            for (String provider : all_providers) {
                Location l = mLocationManager.getLastKnownLocation(provider);
                if (l == null) {
                    continue;
                }
                if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
                    // Found best last known location: %s", l);
                    bestLocation = l;
                }
            }

            if (bestLocation != null) {
                longitude = bestLocation.getLongitude() + "";
                latitude = bestLocation.getLatitude() + "";
            }
        }catch (Exception e) {
            Toast.makeText(RegisterActivity.this,"为稳定匹配合作，请授权访问定位。",Toast.LENGTH_LONG);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {    // 1 for location
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    getCurrentLocation();

                } else {
//                    Log.i("woyaooo", "onRequestPermissionsResult:  fail");
//                    Dialog alertDialog = new AlertDialog.Builder(RegisterActivity.this).
//                            setTitle("信息").
//                            setMessage("为您匹配附近的合作，请授权访问定位").
//                            setIcon(R.drawable.ic_launcher).
//                            setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//
//                                }
//                            }).
//                            create();
//                    alertDialog.show();
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 666 &&   requestCode == MYLOGIN_CODE ) {
            Intent intent = new Intent();
            setResult(666, intent);
            finish();
        }
    }
}
